<!-- 用户档案列表组件 -->
<template>
  <div class="user-archive-list">
    <!-- 搜索区域 -->
    <div class="search-area mb-4 flex items-center gap-4 search-bar">
      <el-input
        v-model="searchForm.name"
        :placeholder="t('healthRecords.placeholders.searchUser')"
        class="w-64"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
        v-model="searchForm.roleCode"
        :placeholder="t('healthRecords.placeholders.selectRole')"
        clearable
        class="w-48"
      >
        <el-option
          v-for="item in userRoleList"
          :key="item.code"
          :label="item.name"
          :value="item.code"
        />
      </el-select>

      <el-select
        v-model="searchForm.attentionType"
        :placeholder="t('healthRecords.placeholders.selectAttention')"
        clearable
        class="w-48"
      >
        <el-option
          v-for="item in attentionTypeList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-button type="primary" @click="handleSearch">
        <el-icon class="mr-1"><Search /></el-icon
        >{{ t("healthRecords.search.search") }}
      </el-button>

      <el-button type="primary" @click="handleReset">
        <el-icon class="mr-1"><Refresh /></el-icon
        >{{ t("healthRecords.search.reset") }}
      </el-button>

      <el-button type="primary" class="ml-auto" @click="handleCreateRecord">
        {{ t("healthRecords.search.createRecord") }}
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      :element-loading-text="t('healthRecords.loading.fetching')"
    >
      <el-table-column
        prop="userId"
        :label="t('healthRecords.table.userId')"
        width="120"
      />
      <el-table-column
        prop="userName"
        :label="t('healthRecords.table.userName')"
        width="120"
      />
      <el-table-column
        prop="familyMemberName"
        :label="t('healthRecords.table.familyMemberName')"
      />
      <el-table-column
        prop="gender"
        :label="t('healthRecords.table.gender')"
        width="80"
      />
      <el-table-column
        prop="birthDate"
        :label="t('healthRecords.table.birthDate')"
        :formatter="formatDate1"
      />
      <el-table-column
        prop="ethnicity"
        :label="t('healthRecords.table.ethnicity')"
        width="100"
      />

      <el-table-column
        :label="t('healthRecords.table.attentionLevel')"
        width="150"
      >
        <template #default="{ row }">
          <EditableRate
            v-model="row.specialAttentionLevel"
            :data-type="4"
            :data-id="row.userId"
          />
        </template>
      </el-table-column>

      <el-table-column
        :label="t('healthRecords.table.riskLevel')"
        prop="riskLevel"
      >
        <template #default="{ row }">
          <span
            :class="{
              'riskLevel-tag': true,
              'riskLevel-tag--sub': row.riskLevel === '良好',
              'riskLevel-tag--normal': row.riskLevel === '轻度风险',
              'riskLevel-tag--chronic':
                row.riskLevel === '高风险' ||
                row.riskLevel === '中高风险' ||
                row.riskLevel === '中度风险'
            }"
          >
            {{ row.riskLevel }}
          </span>
        </template>
      </el-table-column>

      <el-table-column :label="t('healthRecords.table.healthCategory')">
        <template #default="{ row }">
          <span
            :class="{
              'health-tag': true,
              'health-tag--sub': row.healthCategory === '亚健康人群',
              'health-tag--normal': row.healthCategory === '健康人群',
              'health-tag--chronic':
                row.healthCategory === '慢性病人群' ||
                row.healthCategory === '院外恢复期人群' ||
                row.healthCategory === '院外康复期人群',
              'health-tag--doctor':
                row.healthCategory === '门诊就医人群' ||
                row.healthCategory === '急诊就医人群',
              'health-tag--hospital': row.healthCategory === '住院就医人群'
            }"
          >
            {{ row.healthCategory }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        prop="createDate"
        :label="t('healthRecords.table.createDate')"
        width="150"
        :formatter="formatDate"
      />

      <el-table-column
        :label="t('healthRecords.table.actions')"
        fixed="right"
        width="200"
      >
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViewRecord(row)">
            {{ t("healthRecords.actions.viewRecord") }}
          </el-button>
          <el-button type="primary" link @click="handleAddTask(row)">
            {{ t("healthRecords.actions.addToTask") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-end mt-4">
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 任务计划弹窗 -->
    <follow-dialog
      v-model:visible="addTaskDialogVisible"
      :mode="'create'"
      :task-data="[]"
    />
  </div>
</template>

<script lang="ts" setup>
import { healthApi } from "@/api/health";
import { reportApi } from "@/api/report-api";
import { useToolsStore } from "@/store/modules/tools";
import { attentionTypeList as commonAttentionTypeList } from "@/utils/tools";
import FollowDialog from "@/views/followUpPlan/components/followDialog.vue";
import { Refresh, Search } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";

const router = useRouter();

// 国际化
const { t } = useI18n();

// 初始化 store
const toolsStore = useToolsStore();
const dictData = computed(() => toolsStore.getDictData());
// userRoleList
const userRoleList = computed(() => dictData.value.userRoleList);
console.log("dictData", dictData.value);

interface SearchFormType {
  pageNum: number;
  pageSize: number;
  name?: string;
  roleCode?: string;
  attentionType?: string | number;
}

// 搜索表单数据
const searchForm = reactive<SearchFormType>({
  pageNum: 1,
  pageSize: 10,
  name: "",
  roleCode: "",
  attentionType: ""
});

const attentionTypeList = ref(commonAttentionTypeList);

const addTaskDialogVisible = ref(false);

interface HealthArchiveItem {
  userId?: number;
  userName?: string;
  familyMemberName?: string;
  gender?: string;
  birthDate?: string;
  ethnicity?: string;
  specialAttentionLevel?: number;
  riskLevel?: string;
  healthCategory?: string;
  createDate?: string;
  familyId?: number;
}

// 获取字典数据
async function queryDictionaryData() {
  try {
    const response = await reportApi.queryReportDict();
    if (response?.data) {
      toolsStore.setDictData(response.data);
      console.log("获取到的字典数据:", response.data);
    }
  } catch (err) {
    console.error("获取字典数据失败:", err);
    ElMessage.error(t("healthRecords.messages.fetchDictFailed"));
  }
}

// 表格数据
const tableData = ref<HealthArchiveItem[]>([]);

// 加载状态
const loading = ref(false);

// 总条数
const total = ref(0);

// 分页大小改变
const handleSizeChange = (val: number) => {
  searchForm.pageSize = val;
  searchForm.pageNum = 1;
  getHealthArchiveList();
};

const formatDate = (row: HealthArchiveItem) => {
  return row.createDate ? dayjs(row.createDate).format("YYYY-MM-DD") : "";
};

const formatDate1 = (row: HealthArchiveItem) => {
  return row.birthDate ? dayjs(row.birthDate).format("YYYY-MM-DD") : "";
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  searchForm.pageNum = val;
  getHealthArchiveList();
};

// 获取健康档案列表
const getHealthArchiveList = async () => {
  try {
    loading.value = true;
    const response = await healthApi.getHealthArchiveSearch(searchForm);
    if (response.code === 0 && response.data) {
      tableData.value = response.data.list || [];
      total.value = response.data.total || 0;
      // 同步当前页码和每页条数
      searchForm.pageNum = response.data.pageNum;
      searchForm.pageSize = response.data.pageSize;
    } else {
      ElMessage.error(
        response.message || t("healthRecords.messages.fetchArchiveFailed")
      );
    }
  } catch (error) {
    console.error("获取健康档案失败:", error);
    ElMessage.error(t("healthRecords.messages.fetchArchiveFailed"));
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = async () => {
  try {
    searchForm.pageNum = 1;
    await getHealthArchiveList();
  } catch (error) {
    console.error("搜索失败:", error);
    ElMessage.error(t("healthRecords.messages.searchFailed"));
  }
};

// 重置方法
const handleReset = async () => {
  searchForm.name = "";
  searchForm.roleCode = "";
  searchForm.attentionType = "";
  searchForm.pageNum = 1;

  try {
    await getHealthArchiveList();
  } catch (error) {
    console.error("重置失败:", error);
    ElMessage.error(t("healthRecords.messages.resetFailed"));
  }
};

// 创建档案
const handleCreateRecord = () => {
  router.push({
    path: "/healthRecords/createRecord"
  });
};

// 查看档案
const handleViewRecord = async (row: HealthArchiveItem) => {
  try {
    // 参数验证
    if (!row?.userId) {
      ElMessage.warning(t("healthRecords.messages.invalidUserId"));
      return;
    }

    console.log("正在查看档案:", row.userId);
    loading.value = true;

    // 跳转路由
    await router.push({
      path: "/healthRecords/detail",
      query: {
        userId: row.userId
      }
    });
  } catch (error) {
    console.error("查看档案失败:", error);
    ElMessage.error(t("healthRecords.messages.viewFailed"));
  } finally {
    loading.value = false;
  }
};

// 添加任务
const handleAddTask = (row: HealthArchiveItem) => {
  addTaskDialogVisible.value = true;
};

onMounted(() => {
  queryDictionaryData();
  getHealthArchiveList();
});
</script>

<style lang="scss" scoped>
.user-archive-list {
  width: 100%;
  .search-bar {
    margin: 14px 0 16px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 16px;
  }
}
</style>
